//
//  YXLPriceHistoryViewController.m
//  MyNewProject
//
//  Created by 于兴雷 on 2019/2/12.
//  Copyright © 2019年 sun. All rights reserved.
//

#import "YXLPriceHistoryViewController.h"
#import "YXLPriceTableViewCell.h"
#import "YXLHistoryPriceModel.h"
#import "XMAlertView.h"
#import "XMRechargeViewController.h"
#import "HandInPaymentVC.h"

@interface YXLPriceHistoryViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic , retain)UITableView *tableView;

@property (nonatomic , retain)NSMutableArray *dataArry;

@property (nonatomic , retain)NSString  *last_id;

@property (nonatomic , retain)YXLSellModel *sellModel;

@property (nonatomic , retain)UIButton *bottomBtn;

@end

@implementation YXLPriceHistoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.gk_navTitle = @"出价记录";
    self.dataArry = [[NSMutableArray alloc] initWithCapacity:0];
    self.last_id = @"0";
    
    [self initView];
    
    
    [self reloadBottomBtn];
    [self getData];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [YQNetworking cancelRequestWithURL:@"index/getSellLog"];
}
-(void)initView
{
    UITableView *tableView = [[UITableView alloc] init];
    tableView.backgroundColor = SKRGBColor(241, 241, 241);
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.estimatedRowHeight = 0;
    tableView.estimatedSectionFooterHeight = 0;
    tableView.estimatedSectionHeaderHeight = 0;
    if (@available(iOS 11.0, *)) {
        
        tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        
    } else {
        
        self.automaticallyAdjustsScrollViewInsets = NO;
        
    }
    [self.view addSubview:tableView];

    self.tableView = tableView;
    
    UIButton *bottomBtn = [UIButton new];
    bottomBtn.backgroundColor = SKColorWithHex(0xE33030);
    [bottomBtn addTarget:self action:@selector(bottomBtnClick) forControlEvents:UIControlEventTouchUpInside];
    bottomBtn.clipsToBounds = YES;
    [self.view addSubview:bottomBtn];
    self.bottomBtn = bottomBtn;
    bottomBtn.sd_layout
    .leftEqualToView(self.view)
    .rightEqualToView(self.view)
    .bottomSpaceToView(self.view, SKBottomSafe_Height)
    .heightIs(50);
    
    tableView.sd_layout
    .topSpaceToView(self.view, SKTopBar_Height)
    .leftEqualToView(self.view)
    .rightEqualToView(self.view)
    .bottomSpaceToView(self.bottomBtn, 0);
}


-(void)reloadBottomBtn
{
    
    self.bottomBtn.sd_layout
    .heightIs(0);
    self.tableView.sd_layout
    .bottomSpaceToView(self.view, 0);
    
   
}


#pragma mark UITableViewDelegate,UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    //return 10;
    return self.dataArry.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    YXLPriceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    if (!cell) {
        cell = [[YXLPriceTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    YXLHistoryPriceModel *model = self.dataArry[indexPath.row];
    cell.sellModel = self.sellModel;
    
    [cell reloaData:model];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [self cellHeightForIndexPath:indexPath cellContentViewWidth:SCREEN_WIDTH tableView:tableView];
}


-(void)bottomBtnClick
{
    if ([self.refer_price doubleValue] < [self.sellModel.myNewPrice doubleValue]) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"当前出价大于本拍品市场参考价，是否继续出价" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"点击取消");
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"点击确认");
            [self iYaoJingPai];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }
    else
    {
        [self iYaoJingPai];
    }
}
-(void)iYaoJingPai
{
    NSDictionary *paramDic = @{@"uid":self.uid,@"loginKey":self.loginKey,@"sell_id":self.sell_id};
    [YQNetworking postWithUrl:@"index/setSell" params:paramDic reloginRefreshBlock:^(id response) {
        
    } successBlock:^(id response) {
        if ([response[@"status"] isEqualToString:@"lessmoney"]) {
            XMAlertView * alertView = [[XMAlertView alloc]initWithAlertViewWithMsg:@"您的账户保证金不足"];
            [alertView show];
            SKWeakSelf;
            alertView.leftBlock = ^{
                XMRechargeViewController *vc = [[XMRechargeViewController alloc] init];
                vc.paySuccessResultBlock = ^{
                    // 刷新数据
                };
                [weakSelf.navigationController pushViewController:vc animated:true];
            };
        }else if (!IsStrEmpty(response[@"msg"])) {
            [self.view makeToast:SafeString(response[@"msg"]) duration:1 position:CSToastPositionCenter];
        }else {
            
        }
    } failBlock:^(NSError *error) {

    }];
}


-(void)getData
{
    NSDictionary *paramDic = @{@"sell_id":self.sell_id,@"last_id":self.last_id};
    SKWeakSelf;
    [YQNetworking postWithUrl:@"index/getSellLog" refreshRequest:YES cache:NO params:paramDic progressBlock:nil successBlock:^(id response) {
        
        NSDictionary * dataDic = response[@"data"];
        
        weakSelf.last_id = [NSString stringWithFormat:@"%@",dataDic[@"last_id"]];
        
        NSArray *sellLogArry = SafeArray(dataDic[@"sell_log"]);
        
        weakSelf.sellModel =  [YXLSellModel modelWithDictionary:dataDic[@"sell"]];

        NSMutableArray *lastArry = [[NSMutableArray alloc] initWithCapacity:0];
        for (NSDictionary * dic in sellLogArry) {
            YXLHistoryPriceModel * historyPriceModel =  [YXLHistoryPriceModel modelWithDictionary:dic];
            [lastArry addObject:historyPriceModel];
        }
        
        NSInteger count = lastArry.count;
        
        if (count > 0) {
            for (YXLHistoryPriceModel * historyPriceModel in weakSelf.dataArry) {
                historyPriceModel.is_max = @"0";
            }
        }
        for (int i = 0; i<lastArry.count; i++) {
            YXLHistoryPriceModel * historyPriceModel =  lastArry[count-1-i];
            
             [weakSelf.dataArry insertObject:historyPriceModel atIndex:0];
        }
        
        if ([weakSelf.sellModel.lost_end_time integerValue] == 0) {
            
//            weakSelf.sell_Type = 4;
            self.bottomBtn.sd_layout
            .heightIs(0);
            self.tableView.sd_layout
            .bottomSpaceToView(self.view, 0);
        }else{
            self.bottomBtn.sd_layout
            .heightIs(50);
            
            self.tableView.sd_layout
            .bottomSpaceToView(self.bottomBtn, 0);
            [self.bottomBtn setTitle:@"我要竞拍" forState:UIControlStateNormal];

            [weakSelf performSelector:@selector(getData) withObject:nil afterDelay:1];
        }
        
        if (lastArry.count > 0) {
            [weakSelf.tableView reloadData];
        }
        
    } failBlock:^(NSError *error) {
        [weakSelf performSelector:@selector(getData) withObject:nil afterDelay:1];

    }];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
